;(function ($,window,document,undefined){
	
	CP.MainCanvas = function (){
		this.getActiveObject = function (){
			return this.canvas.getActiveObject();
		}
	};
	CP.MainCanvas.prototype.$el = null;
	CP.MainCanvas.prototype.html = '';
	CP.MainCanvas.prototype.canvas = null;
	CP.MainCanvas.prototype.widthCanvas = 500;
	CP.MainCanvas.prototype.heightCanvas = 500;

	CP.MainCanvas.prototype.casePhone = null;
	CP.MainCanvas.prototype.casePhone_mask = null;
	CP.MainCanvas.prototype.maskBackgroundCanvas = null;

	CP.MainCanvas.prototype.centerX = 0;
	CP.MainCanvas.prototype.centerY = 0;

	CP.MainCanvas.prototype.textDict = [];
	CP.MainCanvas.prototype.assetImgDict = [];


	CP.MainCanvas.prototype.init = function (){
		this.html = '<div class="main-canvas-container"><canvas id="{0}" width="{1}" height="{2}"></canvas></div>';
		this.html = this.html.format(MYLIB.constant.main_canvas_id,this.widthCanvas,this.heightCanvas);

		this.$el = $(this.html);

		this.bindEvents();
	}


	CP.MainCanvas.prototype.getElement = function () {

		return this.$el;

	}
	CP.MainCanvas.prototype.getCanvas = function () {

		return this.casePhone;

	}

	//RENDER CANVAS
	CP.MainCanvas.prototype.renderLayout = function () {

		this.canvas = new fabric.Canvas(MYLIB.constant.main_canvas_id,
			{ renderOnAddition: false, hoverCursor: 'pointer', selection: false });
		var that = this;

		this.canvas.on('after:render', function (e) {

		});
		this.canvas.on('before:selection:cleared',function(e){
	
		});
		this.canvas.on({
			'touch:gesture' : function() {
				console.log('TOUCH:GESTURE');
			},
			'touch:drag': function() {
				console.log('TOUCH:DRAG');
			},
			'touch:orientation': function() {
				
			},
			'touch:shake': function() {

			},
			'touch:longpress': function() {

			},     
			'object:selected': function(opt) {
		        //hook up dynamic zorder
				// opt.target.bringToFront();
		    }
		});

	}

	// EVENT
	CP.MainCanvas.prototype.bindEvents = function () {
		MYLIB.eventManager.subscribe(this,MYLIB.eventNames.chooseProductItem,'chooseProductHandle');
		MYLIB.eventManager.subscribe(this,MYLIB.eventNames.saveCanvas,'saveCanvasHandle');
		MYLIB.eventManager.subscribe(this,MYLIB.eventNames.event_submit_text,'addTextHandle');
		MYLIB.eventManager.subscribe(this,MYLIB.eventNames.event_fontSize,'fontSizeHandle');
		MYLIB.eventManager.subscribe(this,MYLIB.eventNames.event_change_color,'changeColorHandle');
		MYLIB.eventManager.subscribe(this,MYLIB.eventNames.event_delete_item,'deleteHandle');
		MYLIB.eventManager.subscribe(this,MYLIB.eventNames.event_duplicate_item,'duplicateHandle');

		//IMAGE UPLOAD
		MYLIB.eventManager.subscribe(this,MYLIB.eventNames.event_upload_from_computer,'addImageUploadHandle');
		MYLIB.eventManager.subscribe(this,MYLIB.eventNames.event_upload_from_asset,'addImageUploadFormAssetHandle');

		$(window).unbind('keydown').bind('keydown',this,this.onKeyDownHandler);

	}
	// HANDLE EVENT
	CP.MainCanvas.prototype.deleteHandle = function (event){
		var activeObject = this.canvas.getActiveObject();
	    if (activeObject){
	    	this.canvas.remove(activeObject);
	    	this.canvas.renderAll();
	    }
	}
	CP.MainCanvas.prototype.duplicateHandle = function (event) {
		var activeObject = this.canvas.getActiveObject();
	        if (activeObject){
	        	var duplicate = fabric.util.object.clone(activeObject);
	        	this.canvas.add(duplicate);
	        	this.canvas.renderAll();
	        }
	}
	CP.MainCanvas.prototype.onKeyDownHandler= function(e) {
		var that = e.data;
	   switch (e.keyCode) {
	      case 46: // delete
	         var activeObject = that.canvas.getActiveObject();
	         if (activeObject){

	         	//IF TEXT
	         	//REMOVE OBJECT FROM CANVAS AND this.TextDict
	         	var activeType = activeObject.type || 'khongro';

	         	switch(activeType){
	         		
	         		case 'MyText':
	    
	         			for (var i = 0; i < that.textDict.length; i++) {
	         				var textId = that.textDict[i].getID();
	         				var activeTextId = activeObject.getID();
	         				if(textId === activeTextId){
	         					console.log('Find');
	         					that.textDict.splice(i, 1)
	         				}
	         			};
	         			console.log(that.textDict);
	         			that.canvas.remove(activeObject);
	         			break;
	         		default:
	         			that.canvas.remove(activeObject);
	         			break;
	         	}

	         }
	         return;
	   }
	}
	CP.MainCanvas.prototype.fontSizeHandle = function (event) {
		var fontSizeValue = event.data;
		console.log(fontSizeValue);
		var activeObject = this.canvas.getActiveObject();

		if (activeObject){

			var activeType = activeObject.type || 'khongro';

         	switch(activeType){
         		
         		case 'text':
         			activeObject.fontSize = fontSizeValue;
         			this.canvas.renderAll()
         			break;
         	}
		}
	}
	CP.MainCanvas.prototype.changeColorHandle = function (event){
		console.log('change color');
		var hexColor = event.data;

		console.log(hexColor);

		var activeObject = this.canvas.getActiveObject();

		if (activeObject){

			activeObject.set({fill : '#'+hexColor});
			this.canvas.renderAll()

		}
	}
	CP.MainCanvas.prototype.chooseProductHandle = function (event) {

		var data = event.data;

		var _this = this;

		this.casePhone_mask = data.product_img_primary_mask;
		
		this.canvas.clear();

		//LOAD IMAGE CASE PHONE
		fabric.Image.fromURL(data.product_img_primary, function(oImg) {

			 _this.canvas.setWidth( _this.widthCanvas )
  		  	_this.canvas.setHeight( _this.heightCanvas )
	  		var numberScale = _this.canvas.width / oImg.width;
			if( numberScale  < 1 ){
					oImg.scale(numberScale);
			}else{
				numberScale = 1;
			}

			_this.casePhone = oImg;
		  	_this.canvas.add(_this.casePhone);
		  	_this.casePhone.selectable  =  false;
		  	_this.centerX = _this.casePhone.currentWidth / 2;
  		  	_this.centerY = _this.casePhone.currentHeight / 2;

  		  	//OVERLAY IMAGE MASK
  		  	_this.canvas.setOverlayImage(data.product_img_primary_mask, _this.canvas.renderAll.bind(_this.canvas),{
				scaleX : numberScale,
				scaleY : numberScale
			} );

			 _this.canvas.setWidth( _this.casePhone.currentWidth )
  		  	_this.canvas.setHeight( _this.casePhone.currentHeight )
			_this.canvas.renderAll();
		});

	}
	CP.MainCanvas.prototype.addTextHandle = function (event) {
		var textValue = event.data;

		var textObj = new fabric.Text(textValue);

		textObj.fontSize = CP_INIT.text.fontSize;
		textObj.fontFamily = CP_INIT.text.fontFamilyDefault;

		textObj.left = this.centerX-50;
		textObj.top = this.centerY-50;


		this.textDict.push(textObj);

		this.canvas.add(textObj);

		this.canvas.renderAll();
	}


	CP.MainCanvas.prototype.addImageUploadHandle = function (event) {
		var that = this;
		var src = event.data;
		var scrCopy = event.data;
		MYLIB.eventManager.fireEvent(that,MYLIB.eventNames.event_display_img,scrCopy)
		
		var imgObj = new Image();
		imgObj.src = src;
		MYLIB.LOADING();
		imgObj.onload = function () {
			MYLIB.REMOVE_LOADING();
		  var image = new fabric.Image(imgObj,{
		  	 	left: that.centerX-100,
  				top: that.centerY-100,
  				centeredScaling : true
  				// scaleX : ( imgObj.width > that.casePhone.width )? (that.casePhone.width / imgObj.width) : 1,
  				// scaleY : ( imgObj.height > that.casePhone.height )? (that.casePhone.height / imgObj.height) : 1
		  });
		  var numberScale = that.casePhone.currentWidth / imgObj.width;
		  if( numberScale  < 1 ){
		  		image.scale(numberScale);
		  }
		  var objcount = that.canvas.getObjects().length;
		  // that.canvas.add(image);

		  // var group = new fabric.Group([image]);

		  that.canvas.add(image);

		  that.canvas.renderAll();

		}
	}

	CP.MainCanvas.prototype.addImageUploadFormAssetHandle = function (event){
		var that = this;
		var src = event.data.src;
		var scrCopy = event.data.src;
		var id = event.data.id;
		var thumb = event.data.thumb;
		MYLIB.eventManager.fireEvent(that,MYLIB.eventNames.event_display_img,scrCopy)
		
		var imgObj = new Image();
		imgObj.src = src;
		MYLIB.LOADING();
		imgObj.onload = function () {
			MYLIB.REMOVE_LOADING();
		  var image = new fabric.Image(imgObj,{
		  	 	left: that.centerX-100,
  				top: that.centerY-100,
  				centeredScaling : true
		  });
		  var numberScale = that.casePhone.currentWidth / imgObj.width;
		  if( numberScale  < 1 ){
		  		image.scale(numberScale);
		  }
		  var objcount = that.canvas.getObjects().length;

		  that.canvas.add(image);

		  that.canvas.renderAll();

		  if(that.assetImgDict){
		  	that.assetImgDict.push({id : id, src : src,thumb : thumb})
		  }
		  console.log(that.assetImgDict);

		}
	}

	//DRAW SHAPE 
	CP.MainCanvas.prototype.drawShape = function (type){
		switch(type){
			case 'CIRCLE':
				// statements_1
				console.log('DRAW CIRCLE NOW');
				var that = this;
				var circle = new fabric.Circle({
				  radius: 50, left: that.centerX-100, top:  that.centerY-100, borderColor  : '#000'
				});
				this.canvas.add(circle);
				this.canvas.renderAll();
				break;
			case 'RECT':
				// statements_1
				console.log('DRAW RECT NOW');
				  var rect = new fabric.Rect({
				    left: 150,
				    top: 200,
				    originX: 'left',
				    originY: 'top',
				    width: 150,
				    height: 120,
				    // angle: -10,
				    fill: 'green',
				    transparentCorners: false
				  });
				this.canvas.add(rect);
				this.canvas.renderAll();
				break;
			default:
				// statements_def
				break;
		}
	}
	//SHOW UP HANDLE
	CP.MainCanvas.prototype.showUpHandle = function (event){
		console.log('SHOW UP ');
		if(this.getActiveObject()){
			this.getActiveObject().bringForward();
		}
		
	}
	CP.MainCanvas.prototype.BackToUpHandle = function (){
		console.log('BACK');
		if(this.getActiveObject()){
			this.getActiveObject().sendBackwards();
		}
	}
	CP.MainCanvas.prototype.rotateRepeatHandle = function (){
		console.log('BACK');
		var that = this;
		if(this.getActiveObject()){
			this.rotateObject(90);
		}
	}

	CP.MainCanvas.prototype.rotateObject = function (angleOffset) {
	    var obj = this.canvas.getActiveObject(),
	        resetOrigin = false;

	    if (!obj) return;

	    var angle = obj.getAngle() + angleOffset;

	    if ((obj.originX !== 'center' || obj.originY !== 'center') && obj.centeredRotation) {
	        obj.setOriginToCenter && obj.setOriginToCenter();
	        resetOrigin = true;
	    }

	    angle = angle > 360 ? 90 : angle < 0 ? 270 : angle;

	    obj.setAngle(angle).setCoords();

	    if (resetOrigin) {
	        obj.setCenterToOrigin && obj.setCenterToOrigin();
	    }

	    this.canvas.renderAll();
	}

	CP.MainCanvas.prototype.saveCanvasHandle = function (event) {
		console.log('SAVE');
		this.canvas.deactivateAll().renderAll();
		var canvas = fabric.util.object.clone(this.canvas);
		// this.casePhone = null;
		canvas.remove(canvas.item(0))
		canvas.setOverlayImage(null)
		var svg = canvas.toSVG();
		// console.log(this.canvas.toSVG());
		console.log(canvas.toDataURL());
	} 

	CP.MainCanvas.prototype.saveCanvasToImg = function (event) {
		this.canvas.deactivateAll().renderAll();
		var svg = this.canvas.toSVG();	
		return this.canvas.toDataURL();
	} 
	MYLIB.mixin(CP.MainCanvas, MYLIB.Event.ObserverMixin);

})(jQuery,window,document)